package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.pojo.dto.categoryDto.CategoryAddDto;
import com.itheima.pojo.dto.categoryDto.CategoryUpdateDto;
import com.itheima.pojo.vo.categoryVo.GetCategoryByPageVo;
import com.itheima.pojo.vo.categoryVo.GetCategoryVo;
import com.itheima.service.CategoryService;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author tcotk
 */
@RestController
public class CategoryController {
    @Resource
    private CategoryService service;


    @PostMapping("/category")
    @ResponseBody
    public R<String> add(@RequestBody CategoryAddDto categoryAddDto) {

        boolean result = service.add(categoryAddDto);
        if (result) {
            return R.success("'分类名'已存在");
        }
        return R.error("存入失败");
    }

    @PutMapping("/category")
    @ResponseBody
    public R<String> update(@RequestBody CategoryUpdateDto category) {
        boolean result = service.update(category);
        if (result) {
            return R.success("修改分类信息成功");
        }
        return R.error("修改失败");
    }

    @DeleteMapping("/category")
    public R<String> delete(String id) {
        boolean result = service.delete(id);
        if (result) {
            return R.success("当前分类下关联了套餐，不能删除");
        }
        return R.error("删除失败");
    }

    @GetMapping("/category/page")
    public R<Object> selectByPage(String name, Integer page, Integer pageSize) {
        List<GetCategoryByPageVo> list = service.selectByPage(name, page, pageSize);

        Map<String, Object> map = new HashMap<>();
        map.put("records", list);
        map.put("total", (page - 1) * pageSize);
        map.put("size", pageSize);
        map.put("current", page);
        return R.success(map);
    }

    @GetMapping("/category/list")
    public R<Object> selectAll() {
        List<GetCategoryVo> list = service.selectAll();
        return R.success(list);
    }


}
